package com.ym.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

public class OssFileUtil {
	public static String DOMAIN = "https://oss-img.ys168.vip/";
	private static String bucketName = "web-new";

	/*
	 * Constructs a client instance with your account for accessing OSS
	 */

	private static OSS init() {
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
		String accessKeyId = "LTAI5t6AJfR9t7YSw6vJ22nA";
		String accessKeySecret = "hzp4iHIeChUlTryppI1c2tBSICD3dI";
		return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
	}

	/*
	 * Upload an object to your bucket
	 */
	public static void putFile(String path, File file) {
		OSS ossClient = init();
		try {
			ossClient.putObject(new PutObjectRequest(bucketName, path, file));
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			ossClient.shutdown();
		}
	}

	/*
	 * Upload an object to your bucket
	 * Set expiration time
	 */
	public static void putFile(String path, File file, int second) {
		OSS ossClient = init();
		try {
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setExpirationTime(DateUtil.addSecond(new Date(), second));
			ossClient.putObject(new PutObjectRequest(bucketName, path, file, metadata));
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			ossClient.shutdown();
		}
	}

	/*
	 * Upload an stream to your bucket
	 */
	public static void putStream(String path, InputStream input) {
		OSS ossClient = init();
		try {
			ossClient.putObject(new PutObjectRequest(bucketName, path, input));
		} catch (Throwable e) {
			throw new RuntimeException(e);
		} finally {
			ossClient.shutdown();
		}
	}
}